package com.bdh.javaBasicStudy;

import org.junit.Test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @projectName: maven_project
 * @package: com.bdh.javaBasicStudy
 * @className: ThreadPoolExer
 * @author: Dream
 * @description: TODO
 * @date: 2022/6/21 13:50
 */
public class ThreadPoolExer {
    //创建线程方式
    @Test
    public void createThread(){
        MyThread myThread1 = new MyThread();
        myThread1.run();
        System.out.println("******************");
        Thread myThread2 = new Thread(new MyRunnable());
        myThread2.run();
        System.out.println("******************");
        FutureTask<Integer> ft = new FutureTask<>(new MyCallable());
        Thread thread3 = new Thread(ft);
        thread3.start();
        try {
            Integer num = ft.get();
            System.out.println("得到的结果" + num);
        }catch (InterruptedException | ExecutionException e){
            e.printStackTrace();
        }
    }
    //继承Thread
    public class MyThread extends Thread{
        @Override
        public void run() {
            System.out.println("输出");
            for (int i = 0; i < 1000; i++) {
                System.out.print(i);
            }
        }
    }
    //实现Runnable接口
    static class MyRunnable implements Runnable{
        @Override
        public void run() {
            System.out.println("输出");
            for (int i = 0; i < 1000; i++) {
                System.out.print(i);
            }
        }
    }
    //如果需要一个返回值的话
    public class MyCallable implements Callable<Integer>{
        @Override
        public Integer call() throws Exception {
            int num = 0;
            for (int i = 0; i < 1000; i++) {
                System.out.print(i);
                num += i;
            }
            return num;
        }
    }


    //现有线程T1\T2\T3。保证T2在T1执行完后执行，T3在T2执行完后执行
    @Test
    public void JoinExer(){
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                System.out.println("t1=====>" + i);
            }
        });
        Thread t2 = new Thread(() -> {
            try {
                t1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < 3; i++) {
                System.out.println("t2=====>" + i);
            }
        });
        Thread t3 = new Thread(() -> {
            try {
                t2.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < 3; i++) {
                System.out.println("t3=====>" + i);
            }
        });
        t1.start();
        t2.start();
        t3.start();
    }

}
